package top.chendawei.aop.auth;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import top.chendawei.aop.bus.GuavaBus;
import top.chendawei.aop.exceptions.CommonPartsExceptions;
import top.chendawei.main.facade.UserFacadeImpl;
import top.chendawei.system.beans.entity.OperationLog;
import top.chendawei.system.beans.entity.SysUser;
import top.chendawei.system.util.annotation.SysLog;
import top.chendawei.util.DateUtils;
import top.chendawei.util.http.HttpServletUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

@Slf4j
public class AuthorizeInterceptor implements HandlerInterceptor {

    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Autowired
    private UserFacadeImpl userFacade;
    @Autowired
    CustomsSecurityProperties customsSecurityProperties;


    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        response.setCharacterEncoding("UTF-8");
//        response.setContentType("text/html;charset=UTF-8");
        String uri = request.getRequestURI();
        boolean goon = true;
        if (null != customsSecurityProperties.getPermitAllUrls() && customsSecurityProperties.getPermitAllUrls().length > 0) {
            for (String s : customsSecurityProperties.getPermitAllUrls()) {
                if ("/".equals(uri) || antPathMatcher.match(s, uri)) {
                    goon = false;
                    break;
                }
            }
        }

        if (goon && null != customsSecurityProperties.getPermitAccessUrls() && customsSecurityProperties.getPermitAccessUrls().length > 0) {
            for (String s : customsSecurityProperties.getPermitAccessUrls()) {
                if (StringUtils.isNoneBlank(s) && antPathMatcher.match(s, uri)) {
                    goon = false;
                    break;
                }
            }
        }
        //二次校验权限
        if (goon) {
            SysUser user = userFacade.getUserFromToken(request);
            if (user == null) {
                this.log.debug(uri + " ...  user is null");
                throw new CommonPartsExceptions("请重新登陆");
            }
            boolean checkAuth = userFacade.queryCheckAuth(uri, user.getRoleIdList());
            if (!checkAuth) {
                throw new CommonPartsExceptions("无该接口权限");
            }
            this.log.debug(uri + "====到死也没有拦截到");
        }
        return true;
    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        SysUser user = userFacade.getUserFromToken(request);
        if (user != null) {
            Method method = handlerMethod.getMethod();
            SysLog log = method.getAnnotation(SysLog.class);
            if (log != null) {
                String descript = log.description();
                sendOpLog(descript, request, user);
            }
        }
    }

    private void sendOpLog(String descript, HttpServletRequest request, SysUser user) {
        OperationLog oLog = new OperationLog();
        String uri = request.getRequestURI();
        oLog.setUserid(user.getUsername());
        oLog.setUpdateDate(DateUtils.getCurrDate(null));
        String ip = HttpServletUtil.getIpFromRequest(request);
        oLog.setIp(ip);
        oLog.setUri(uri);
        oLog.setStatus(0);
        oLog.setDescript(descript);
        GuavaBus.post(oLog);
    }

}
